<template>
  <div class="chart-container">
    <p class="chart-title">诊断与建议</p>
    <div ref="chartElement" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "DiagnosisGridChart",
  props: {
    gridData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chartInstance: null,
      options: { // Base options structure
        toolbox: {
          show: false,
          feature: {
            // dataZoom: { yAxisIndex: 'none' }, // Zoom might not be ideal for grid
            dataView: { readOnly: true },
            saveAsImage: {}
          },
        },
        tooltip: {
          position: 'top',
          formatter: function (params) {
            if (!params.data || !params.data.info) return ''; // Basic check
            const info = params.data.info;
            let describe = '';
            if(params.data.checked === 1){
              describe = '当前预测模式'
            }else if(params.data.checked === 2){
              describe = '优化方向模式'
            }else{
              describe = '无'
            }
            return `
              <div style="padding: 5px; border: 1px solid #ccc; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <div style="font-weight: bold; margin-bottom: 5px; color: #333;">${info.title || '详情'}</div>
                <div style="font-size: 0.9em; color: #555;">类别名：${info.name || '-'}</div>
                <div style="font-size: 0.9em; color: #555;">优化效果：${info.status || '-'}</div>
                <div style="font-size: 0.9em; color: #555;">说明：${describe}</div>
              </div>
            `;
          },
          backgroundColor: 'transparent', // Make tooltip background transparent
          borderColor: 'transparent', // Hide border
          textStyle: { color: '#333' }, // Ensure text is visible
          extraCssText: 'box-shadow: none;' // Remove default shadow if needed
        },
        animation: false,
        xAxis: {
          name: '总焦比',
          nameLocation: 'middle',
          nameGap: 25, // Adjusted gap
          nameTextStyle: { fontSize: 12 },
          type: 'category',
          data: ['[大于350]','[335-350]','[320-335]','[305-320]','[小于305]'],
          splitArea: { show: true, areaStyle: { color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.1)'] } }, // Subtle split area
          axisLine: { show: true, lineStyle:{ color: '#666'} }, // Show axis line
          axisTick: { show: false }, // Hide ticks
          axisLabel: {
            interval: 0,
            rotate: 0,
            formatter: function(value) { return value.split('\n').join('\n'); },
            fontSize: 11 // Slightly smaller labels
          }
        },
        yAxis: {
          name: '利用系数',
          nameLocation: 'middle',
          nameGap: 35, // Increased gap
          nameTextStyle: { fontSize: 12 },
          type: 'category',
          data: ['[2.2-2.4]','[2.0-2.2]','[1.8-2.0]','[1.5-1.8]'],
          splitArea: { show: true, areaStyle: { color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.1)'] } }, // Subtle split area
          axisLine: { show: true, lineStyle:{ color: '#666'} }, // Show axis line
          axisTick: { show: false }, // Hide ticks
          axisLabel: {
            interval: 0,
            rotate: 0,
            formatter: function(value) { return value.split('\n').join('\n'); },
            fontSize: 11 // Slightly smaller labels
          }
        },
        grid: {
          top: '5%', // Adjusted margins
          bottom: '5%',
          left: '5%',
          right: '5%',
          containLabel: true,
          borderColor: '#ccc', // Lighter border
          borderWidth: 1,
          show: true
        },
        series: [{
          type: 'scatter',
          symbol: 'rect',
          symbolSize: [55, 45], // Adjusted symbol size slightly
          data: [], // Will be populated by props
          label: {
            show: true,
            formatter: function (params) {
              // Ensure info and name exist, handle potential line breaks
              return params.data?.info?.name?.split('\n').join('\n') || '';
            },
            color: '#303133',
            fontSize: 9, // Smaller font size for label inside rect
            overflow: 'break', // Allow text to break
            width: 50, // Constrain width
            lineHeight: 11
          },
          itemStyle: {
            color: function (params) {
              switch(params.data.checked) {
                case 1: return '#409EFF'; // Element UI Primary Blue
                case 2: return '#67C23A'; // Element UI Success Green
                default: return '#F5F7FA'; // Element UI Light Grey
              }
            },
            borderWidth: 1, // Add border to rectangles
            borderColor: '#ddd' // Light border color
          },
          emphasis: {
            itemStyle: {
              borderColor: '#333', // Darker border on hover
              borderWidth: 1.5,
              shadowBlur: 5,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            },
            label: {
              color: '#000', // Ensure label is visible on hover emphasis
              fontWeight: 'bold'
            }
          }
        }]
      }
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
    this.updateChart(); // Initial update
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chartInstance?.dispose();
  },
  watch: {
    gridData: {
      deep: true,
      handler() {
        this.updateChart();
      }
    }
  },
  methods: {
    initChart() {
      if (!this.$refs.chartElement) return;
      // Delay initialization slightly to ensure DOM element is ready
      this.$nextTick(() => {
        try {
          this.chartInstance = echarts.init(this.$refs.chartElement);
          this.chartInstance.setOption(this.options); // Set base options
          this.updateChart(); // Then apply data
        } catch (error) {
          console.error("Failed to initialize GridChart:", error);
        }
      });
    },
    updateChart() {
      if (!this.chartInstance || !this.gridData || this.gridData.length === 0) {
        // Optionally clear the chart or show a message if data is empty
        if (this.chartInstance) {
          this.chartInstance.setOption({ series: [{ data: [] }] });
        }
        return;
      }

      const formattedData = [];
      const rowCount = this.gridData.length;
      const colCount = this.gridData[0].length; // Assume grid is not empty

      for (let row = 0; row < rowCount; row++) {
        for (let col = 0; col < colCount; col++) {
          // Basic check if gridData[row] and gridData[row][col] exist
          if(this.gridData[row] && this.gridData[row][col]) {
            const cellData = this.gridData[row][col];
            formattedData.push({
              // Echarts scatter needs [x, y] where x is col index, y is row index
              value: [col, row],
              // Pass other data needed for tooltip/styling
              checked: cellData.checked,
              info: cellData.info || { title: 'N/A', name: '', status: 'N/A' } // Provide default info
            });
          } else {
            console.warn(`Missing data at gridData[${row}][${col}]`);
          }
        }
      }

      // 计算符号大小，确保横向和纵向间距一致
      const gridWidth = this.chartInstance.getWidth() * (1 - parseFloat(this.options.grid.left)/100 - parseFloat(this.options.grid.right)/100);
      const gridHeight = this.chartInstance.getHeight() * (1 - parseFloat(this.options.grid.top)/100 - parseFloat(this.options.grid.bottom)/100);

      // 使用相同的比例因子计算宽度和高度
      const spacingFactor = 0.7; // 调整这个值可以控制间距大小
      const symbolWidth = Math.max(10, Math.floor(gridWidth / colCount * spacingFactor));
      const symbolHeight = Math.max(10, Math.floor(gridHeight / rowCount * spacingFactor));


      this.chartInstance.setOption({
        series: [{
          // Update only the data and potentially symbolSize
          data: formattedData,
          symbolSize: [symbolWidth, symbolHeight],
          label: {
            width: symbolWidth * 0.9, // Adjust label width based on symbol size
            fontSize: Math.min(11, symbolHeight * 0.2) // Adjust font size based on height
          }
        }]
      });
    },
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
        // Recalculate symbol size after resize
        this.updateChart(); // Re-calling updateChart will recalculate symbolSize
      }
    }
  }
};
</script>

<style scoped>
/* Use same styles as TemperatureChart */
.chart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 200px;
}
.chart-title {
  text-align: center;
  margin: 2px 0; /* 减小上下边距 */
  font-size: 0.9em; /* 减小字体大小 */
  font-weight: bold;
  color: #333;
  line-height: 1.2; /* 减小行高 */
}
.chart {
  flex-grow: 1;
  width: 100%;
  height: 100%;
}
</style>
